#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include "str.h"
#include "tag.h"
#include "lex.h"
#include "parse.h"


int main ( int argc, char *argv[] )
{
	FILE *stream_in = 0;
	FILE *stream_out = stdout;
  FILE *stream_lock = 0;

	char c;
	while( (c=getopt(argc,argv,"o:l:")) != -1 )
	{
		switch(c)
		{
			case 'o':
				{
					stream_out = fopen( optarg, "w" );
					if ( !stream_out )
					{
						fprintf( stderr, "failed opening '%s'\n", optarg );
						exit(EXIT_FAILURE);
					}
				}
				break;
			case 'l':
				{
					stream_lock = fopen( optarg, "r" );
					if ( !stream_lock )
					{
						fprintf( stderr, "failed opening '%s'\n", optarg );
						exit(EXIT_FAILURE);
					}
				}
        break;
		}
	}


	int narg = argc - optind;


	if ( narg < 1 )
	{
		stream_in = stdin;
	}
	else if (narg == 1)
	{
		stream_in = fopen( argv[optind], "r" );
		if ( !stream_in )
		{
			fprintf( stderr, "failed opening '%s'\n", argv[optind] );
			exit(EXIT_FAILURE);
		}
	}
	else
	{
		fprintf( stderr, "usage: %s FILE\n", argv[0] );
		return EXIT_FAILURE;
	}


	tstack_t ts = DEFAULT_TSTACK;
	lex_xref(stream_in,stream_out,stream_lock,&ts,&parse_xref);


#if 0
	tstack_t ts_inv;
	tstack_invert(&ts_inv,&ts);
	tstack_free(&ts);

	tag_t tag = DEFAULT_TAG;
	while ( tstack_pop( &ts_inv,&tag) )
	{
		printf( "pop %s\t\tend=%d\t\tsync=%d\n", tag.name, tag.end, tag.sync );
		if ( tag.nattrs )
		{
			printf( "attrs (%d):\n", tag.nattrs );
			for ( int i = 0; i < tag.nattrs; i++ )
				printf( "%s = %s\n", tag.attrs[i].key,
						tag.attrs[i].val );
		}
		if ( tag.tok.init && !is_blank(&tag.tok) )
		{
			printf( "tok (%d):\n", tag.tok.n );
			printf( "'%s'\n", tag.tok.v ); 
		}
	}
#endif

	fclose(stream_in);
	fclose(stream_out);
  if ( stream_lock )
    fclose(stream_lock);
	return EXIT_SUCCESS;
}
